package com.dduggs.utils;

import com.alibaba.com.caucho.hessian.io.*;
import org.slf4j.*;

import java.io.*;

/**
 * hessian序列化工具类
 */
public class HessianUtils {

	private final static Logger logger = LoggerFactory.getLogger(HessianUtils.class);

	/**
	 * hessian serializer factory
	 */
	private static final SerializerFactory serializerFactory = new SerializerFactory();

	public static byte[] encode(Object obj) throws IOException {

		ByteArrayOutputStream os = new ByteArrayOutputStream(1024);

		Hessian2Output h2o = new Hessian2Output(os);
		h2o.setSerializerFactory(serializerFactory);

		try {
			h2o.writeObject(obj);
		} finally {

			closeQuietly(h2o,os);
		}

		return os.toByteArray();
	}

	@SuppressWarnings("unchecked")
	public static <T> T decode(byte[] data) throws IOException {

		Object obj = null;

		ByteArrayInputStream in = new ByteArrayInputStream(data);

		Hessian2Input hessian2Input = new Hessian2Input(in);
		hessian2Input.setSerializerFactory(serializerFactory);

		try {
			obj = hessian2Input.readObject();
		} finally {

			closeQuietly(hessian2Input,in);
		}

		return (T) obj;
	}

	private static void closeQuietly(Hessian2Output hessian2Output,Closeable closeable) {

		try {

			try {
				if(closeable != null) {
					closeable.close();
				}
			} catch (IOException var2) {

			}

			if (hessian2Output != null) {
				hessian2Output.close();
			}
		} catch (IOException e) {
			logger.warn("close hessian2Output failed");
		}
	}

	private static void closeQuietly(Hessian2Input hessian2Input,Closeable closeable) {

		try {
			if(closeable != null) {
				closeable.close();
			}
		} catch (IOException var2) {

		}
		try {
			if (hessian2Input != null) {
				hessian2Input.close();
			}
		} catch (IOException e) {
			logger.warn("close hessian2Input failed");
		}
	}

}